<template>
  <div class="task">
    <div class="task-header">
      <h1>TODO LIST</h1>
      <input type="text" v-model="task" placeholder="请输入任务" />
      <button @click="addTask">添加</button>
      <button @click="deleteAllTask">删除所有</button>

      <div class="task-list">

        <div class="task-item" v-for="item in taskList" :key="item.id">
          <span v-if="isShowUpdate !== item.id">{{ item.taskname }}</span>
          <button @click="showUpdate(item.id)" v-if="isShowUpdate !== item.id">修改</button>
          
          <div v-if="isShowUpdate === item.id">
            <input type="text" v-model="taskupdata" placeholder="请输入任务" />
            <button @click="updateTask(item.id)">保存</button>
          </div>

          <button @click="deleteTask(item.id)" v-if="isShowUpdate !== item.id">删除</button>
        </div>

      </div>

    </div>
  </div>
</template>

<style scoped>
.task {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
}

.task-header {
  padding: 20px;
  width: 700px;
  height: 400px;
  background-color: #9fcdff;
  border-radius: 20px;
}

.task-header input {
  width: 300px;
  height: 30px;
  border-radius: 5px;
  border: 2px solid #b2b2b2;
}

.task-header button {
  margin: 0 0 0 10px;
  width: 70px;
  height: 30px;
  border-radius: 5px;
  border: 1px solid #b2b2b2;
  cursor: pointer;
}
</style>

<script>
import axios from 'axios';
import { ref } from 'vue';
export default {
  data() {
    return {
      taskList: [],
      task: "",
      isShowUpdate :ref(-1),
      taskupdata: ""
    }
  },
  methods: {
    addTask() {
      axios.post('http://localhost:3080/task/addTask', {
        task: this.task
      }).then(res => {
        if (res.data === "添加任务成功") {
          location.reload();
        } else {
          alert(res.data);
        }
      })
    },
    deleteAllTask() {
      axios.post('http://localhost:3080/task/deleteAllTask').then(res => {
        alert(res.data);
        location.reload();
      })
    },
    deleteTask(id) {
      axios.post('http://localhost:3080/task/deleteTask', { id }).then(res => {
        location.reload();
      })
    },
    showUpdate(id){
      this.isShowUpdate = id;
    },
    updateTask(id) {
      axios.post('http://localhost:3080/task/updateTask', {
        id,
        task: this.taskupdata
      }).then(res => {
        location.reload();
      })
    }
  },
  mounted() {
    axios.get('http://localhost:3080/task/getAllTask').then(res => {
      this.taskList = res.data;
    })
  }
}
</script>
